from flask import request, g, redirect

from application import app
from common.libs.UrlManager import UrlManager
from common.libs.UserService import UserService
from common.models.user import User
from common.models.user_info import UserInfo


@app.before_request
def before_request():
    app.logger.info("=======before_request========")
    user_info = check_login()
    app.logger.info(user_info)
    g.current_user = None
    app.logger.info(request.path)
    if user_info:
        g.current_user = user_info
    else:
        """
        鉴权措施
        """
        if '/info' in request.path:
            return redirect(UrlManager.buildUrl('/error/401'))
    return


@app.after_request
def after_request(response):
    app.logger.info("=======after_request========")
    return response


"""
判断用户是否登录
"""


def check_login():
    cookies = request.cookies
    # print(cookies)
    cookie_name = app.config['AUTH_COOKIE_NAME']
    auth_cookie = cookies[cookie_name] if cookie_name in cookies else None
    # print(auth_cookie)
    if auth_cookie is None:
        return False
    auth_info = auth_cookie.split('#')
    # app.logger.info(auth_info)
    if len(auth_info) != 2:
        return False
    try:
        login_info = User.query.filter_by(id=auth_info[1]).first()
    except Exception:
        return False
    if login_info is None:

        return False

    if auth_info[0] != UserService.geneAuthCode(login_info):

        return False
    info = UserInfo.query.filter_by(login_id=login_info.id).first()
    return info
